package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.article.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.common.wemedia.NewsAutoScanConstants;
import com.heima.common.wemedia.NewsUpOrDownConstants;
import com.heima.common.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 参数检查
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 分页检查
        dto.checkParam();
        IPage<WmNews> pageParam = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 根据状态精确查询
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        // 根据频道精确查询
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        // 根据时间范围查询
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubdate() != null, WmNews::getPublishTime, dto.getBeginPubdate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubdate() != null, WmNews::getPublishTime, dto.getEndPubdate());
        // 关键字模糊查询
        wrapper.like(dto.getKeyWord() != null, WmNews::getTitle, dto.getKeyWord());
        //查询当前用户的登录信息
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        //根据日期排序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        //构建分页查询
        IPage<WmNews> page = page(pageParam, wrapper);
        //结果封装返回
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal());
        result.setData(page.getRecords());
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章标题或内容 不能为空");
        }
        //校验是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //文章布局为自动
        if (dto.getType() == -1) {
            wmNews.setType(null);
        }
        String images = imageListToStr(dto.getImages());
        wmNews.setImages(images);
        wmNews.setUserId(user.getId());
        //保存文章
        saveWmNews(wmNews, dto.getStatus());
        // 如果是草稿  直接返回
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // TODO 3.1 抽取文章中关联的图片路径
        List<String> materials = parseContentImage(dto.getContent());
        // TODO 3.2 关联文章内容中的图片和素材关系
        if (!CollectionUtils.isEmpty(materials)) {
            saveRelativeInfo(materials, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // TODO 3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(dto, materials, wmNews);

        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult<WmNews> findWmNewsById(Integer id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNewById(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //获取文章数据
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章状态 9 已发布/已上架 无法删除
        if (wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //删除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        //上架
        if (enable == null || (!WemediaConstants.WM_NEWS_UP.equals(enable) &&
                !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //判断文章是否发布
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态,无法上下架");
        }
        //修改文章状态
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));
        //向ES同步上下架消息
        if (wmNews.getArticle_id() != null) {
            if (enable.equals(WemediaConstants.WM_NEWS_UP)) {
                //发送上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY, wmNews.getArticle_id());
            }
            if (enable.equals(WemediaConstants.WM_NEWS_DOWN)) {
                //发送下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY, wmNews.getArticle_id());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
        Page<WmNewsVo> page = new Page<>(dto.getPage(), dto.getSize());
        List<WmNewsVo> info = wmNewsMapper.findListByPage(page, dto);
        Long count = wmNewsMapper.findListCount(dto);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), count, info);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult<WmNewsVo> findOne(Integer id) {
        //1参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById((Serializable) wmNews.getUserId());
        }
        WmNewsVo wmNewsVo = WmNewsVo.builder().authorName(wmUser.getName()).build();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        return ResponseResult.okResult(wmNewsVo);
    }

    @Override
    public ResponseResult updateStatus(NewsAuthDto dto, Short status) {
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章是否存在
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章状态 只要不为9(已发布) 都能进行人工审核
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(dto.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已发布,不能进行审核!");
        }
        //修改文章状态
        wmNews.setStatus(status);
        //如果是人工审核失败,set拒绝理由
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        // TODO 通知定时发布文章
        long publishTime = wmNews.getPublishTime().getTime();

        long nowTime = new Date().getTime();
        long remainTime = nowTime - publishTime;
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY, wmNews.getId(),
                msg -> {
                    msg.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                    return msg;
                });
        log.info("文章将在{}  后发布~~~", remainTime);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateWmNews(WmNews wmNews) {
        updateById(wmNews);
        return ResponseResult.okResult();

    }

    /**
     * 【3.3】 关联文章封面中的图片和素材关系
     *
     * @param dto       前端用户选择封面信息数据
     * @param materials 从内容中解析的图片列表
     * @param wmNews    文章ID
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        //获取用户选择的图片
        List<String> images = dto.getImages();
        //判断图文类型
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //图文类型为单图
            if (materials.size() > 0 && materials.size() <= 2) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (materials.size() > 2) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        // 保存图片列表和素材的关系
        if (images != null && images.size() > 0) {
            images = images.stream().map(x -> x.replace(webSite, "")
                    .replace(" ", "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存素材和文章关系
     *
     * @param urls   素材列表
     * @param newsId 文章ID
     * @param type   类型 0：内容素材  1：封面素材
     */
    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
        Integer userId = WmThreadLocalUtils.getUser().getId();
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urls, userId);
        //判断素材是否缺失
        if (CollectionUtils.isEmpty(ids) || ids.size() < urls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "相关素材缺失,保存文章失败");
        }
        //3 保存素材关系
        wmNewsMaterialMapper.saveRelations(ids, newsId, type);
    }

    /**
     * 抽取文章内容中 所引用的所有图片
     *
     * @param content 文章内容
     * @return
     */
    private List<String> parseContentImage(String content) {
        //将String转换成Map
        List<Map> contents = JSON.parseArray(content, Map.class);
        // 遍历文章内容   将所有 type为image的 value获取出来  去除前缀路径
        return contents.stream().filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE))
                //获取value的url字符串
                .map(e -> (String) e.get("value"))
                //去掉前缀路径
                .map(url -> url.replace(webSite, "")).distinct().collect(Collectors.toList());
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews 文章对象（前端传递）
     */
    private ResponseResult<WmNews> saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setStatus(isSubmit);
        //上架
        wmNews.setEnable(Integer.valueOf(WemediaConstants.WM_NEWS_UP));
        //保存
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            //修改,当前文章删除素材库关联
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wmNewsMaterialMapper.delete(wrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 图片列表转字符串，并去除图片前缀
     *
     * @param images 图片列表
     * @param
     */
    private String imageListToStr(List<String> images) {
        //将images中所有前缀webSite替换成空字符串,用","分隔
        return images.stream().map(url -> url.replace(webSite, ""))
                .collect(Collectors.joining(","));
    }
}
